//
//  BTTrainingCampVC.m
//  BaxTer
//
//  Created by wsj2015 on 16/10/31.
//  Copyright © 2016年 陈武琦. All rights reserved.
//

#import "BTTrainingCampVC.h"
#import "BTTrainningCampCell.h"
#import "BTTraniningModel.h"
#import "BTSuperCollectView.h"
#import "BTTrainingCampTool.h"
#import "BTTrainingVC.h"
#import "BTCourseDetailVC.h"
#import "BTTopicDetailVC.h"
#import "WSJPopview.h"
#import "BTBaseWebVC.h"
#import "BerizeHeader.h"
#import "NSString+Utilities.h"
#import "UIImageView+BTimageView.h"
@interface BTTrainingCampVC ()<UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (weak, nonatomic) IBOutlet BerizeHeader *header;
@property (weak, nonatomic) IBOutlet UILabel *titleL;
@property (weak, nonatomic) IBOutlet UIImageView *iconView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topToheader;

@property (nonatomic,  strong) UIColor *themColor;
@property (weak, nonatomic) IBOutlet BTSuperCollectView *collectonView;

@property (nonatomic,  strong) BTTraniningModel *trainingDetail;
@property (weak, nonatomic) IBOutlet UILabel *stepL;

@property (weak, nonatomic) IBOutlet UILabel *daojishi;

@property (nonatomic,  strong) BTTrainingStapModel *currentStap;

@property (nonatomic,  strong)  NSArray *positionArray;


@end

@implementation BTTrainingCampVC


- (void)configUI{
    
    CGFloat space = 4 * 4 + 40;
    CGFloat w = (kScreenWidth - space)/5;
    CGFloat f = kScreenFactor;
    self.topToheader.constant = self.topToheader.constant *f;
    self.flowLayout.itemSize = CGSizeMake( w, w);
     [self.collectonView registerNib:[UINib nibWithNibName:@"BTTrainningCampCell" bundle:nil] forCellWithReuseIdentifier:@"BTTrainningCampCell"];
    self.iconView.layer.cornerRadius = self.iconView.width/2;
    self.iconView.layer.masksToBounds = YES;
   
//    weakSelf_define;
//    [self.collectonView wsj_HeaderRefreshBlock:^{
//        [weakSelf requestTrainingDetail];
//        
//    }];

}

- (NSArray *)positionArray{
   
    if (!_positionArray) {
        _positionArray = @[@(1),@(21),@(6),@(22),@(11),@(15),@(5),@(18),@(2),@(10),@(16),@(8),@(0),@(9),@(24),@(12),@(3),@(23),@(19),@(7),@(20),@(17),@(13),@(4),@(14)];
    }
    return _positionArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    switch (self.trainingType) {
        case BTTrainingCampVCType_1:
            self.themColor = [UIColor greenColor];
            break;
        case BTTrainingCampVCType_2:
            
            break;
        case BTTrainingCampVCType_3:
            
            break;
        case BTTrainingCampVCType_4:
            
            break;
            
        default:
            break;
    }
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.trainingType = BTTrainingCampVCType_1;
    }
    return self;
}


- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (IBAction)gotoTrainingListVC:(id)sender {
    BTTrainingVC *vc = [BTTrainingVC new];
    weakSelf_define;
    vc.selectBlock = ^(NSInteger campId){
        weakSelf.trainingId = campId;
      
    };
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)requestTrainingDetail{
    self.collectonView.loading = YES;
    weakSelf_define;
    if (!self.trainingDetail) {
        [self wsj_showLodingGif];
    }
    
    [[BTNetworkManager sharedMg] POST:kTrainingDetail parameters:@{@"campId":@(self.trainingId)} success:^(NSDictionary * responseObject) {
        if (!self.trainingDetail) {
            [self wsj_hideLodingGif];
        }
        [weakSelf.collectonView.header endRefreshing];
        weakSelf.collectonView.loading = NO;
        if (responseObject_success) {
          
            [weakSelf.dataArray removeAllObjects];
                      NSDictionary *dataDict = responseObject[@"data"];
            if ([dataDict isKindOfClass:[NSDictionary class]]) {
                if ([dataDict isKindOfClass:[NSDictionary class]]) {
                    weakSelf.trainingDetail  = [BTTraniningModel mj_objectWithKeyValues:dataDict];
                    [BTTrainingCampTool saveLastTrainingCampId:[weakSelf.trainingDetail.id integerValue]];
                  
                    weakSelf.titleL.text = weakSelf.trainingDetail.campName;
                }
                if ([dataDict[@"campUserSteps"] isKindOfClass:[NSArray class]]) {
                    weakSelf.trainingDetail.campUserSteps = [BTTrainingStapModel  mj_objectArrayWithKeyValuesArray:dataDict[@"campUserSteps"]];
                    [weakSelf randomPostion];
                }
                weakSelf.themColor = [NSString colorWithHexString:weakSelf.trainingDetail.campColor];
               
                [weakSelf freshUI];
                [weakSelf.collectonView reloadData];
            }
           
        }
      
     
    } failure:^(NSString *err) {
        if (!self.trainingDetail) {
            [self wsj_hideLodingGif];
        }
        weakSelf.collectonView.loading = NO;
       [weakSelf.collectonView.header endRefreshing];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)setThemColor:(UIColor *)themColor{
    if (!themColor && ![themColor isKindOfClass:[NSNull class]]) {
        _themColor = kMainColor;
    }else{
        _themColor = themColor;
    }
}

- (void)freshUI{
 
    if (self.trainingDetail.campUserSteps.count == 0) {
        return;
    }
     [self.header showAnimtionWithColor:self.themColor];
    __block NSInteger alreadyStaps = 0;
    __block NSInteger currentstapIndex = -1;
    __block BOOL isAppear = 0;
    //按照数组下标来计算  1 ,1 ,1,0 ,0
    [self.trainingDetail.campUserSteps enumerateObjectsUsingBlock:^(BTTrainingStapModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        
        if ([obj.status integerValue] == 0) {
          
            if (isAppear == NO) {
                currentstapIndex = idx;
                isAppear = YES;
            }
            
        }else{
           alreadyStaps ++ ;
        }
    }];
    
    [self.iconView bt_setImageWithUrl:self.trainingDetail.campIcon];
    self.stepL.textColor = self.themColor;
    self.daojishi.textColor = self.themColor;
    self.stepL.text = [NSString stringWithFormat:@"关卡: %@/%@",@(alreadyStaps),@(self.self.trainingDetail.campUserSteps.count)];
    if ([self.trainingDetail.status integerValue] == 1) {
        self.daojishi.text = @"恭喜您完成本阶段内容!";
       
    }else{
        if (currentstapIndex
             != -1) {
             BTTrainingStapModel *model = self.trainingDetail.campUserSteps[currentstapIndex];
             self.currentStap = model;
             self.daojishi.text = [NSString stringWithFormat:@"当前阶段倒计时: %@ 天", model.expireDays?model.expireDays:@(0)];
        }else{
            self.currentStap = nil;
             self.daojishi.text = @"";
        }
       
    }
   
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    //    return self.dataArray.count;
    return  25;
}

- (void)randomPostion{
   
    
    if (self.trainingDetail.campUserSteps.count == 0) {
        return;
    }
   
   
   

    [self.trainingDetail.campUserSteps enumerateObjectsUsingBlock:^(BTTrainingStapModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [self.positionArray enumerateObjectsUsingBlock:^(NSNumber * _Nonnull num, NSUInteger jdx, BOOL * _Nonnull stop) {
            if ([obj.campStepIndex integerValue] == num.integerValue) {
                obj.postion = jdx;
            }
        }];
        

    }];
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    BTTrainningCampCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"BTTrainningCampCell" forIndexPath:indexPath];
 
     cell.position = indexPath.row;
//    if (indexPath.row <= self.trainingDetail.campUserSteps.count) {
//        
//    }
  
    cell.contentView.backgroundColor = self.themColor;
    if (indexPath.row == 12) {
        if ([self.trainingDetail.status integerValue] == 1) {
            cell.imageIcon.image = [UIImage imageNamed:@"camp_cup_light"];
        }else{
            cell.imageIcon.image = [UIImage imageNamed:@"camp_cup"];
        }
        
    }else{
        
        
          NSInteger position = indexPath.row;
     
        
        
        NSArray *arr =  self.trainingDetail.campUserSteps;
        BOOL isExit = NO;
        for (int i = 0 ; i< arr.count; i ++) {
            BTTrainingStapModel * obj = arr[i];
            if (obj.postion == position) {
                
                WSJLog(@"我是 低%@个格子",@(position));
                if ([obj.status integerValue] == 0) {
                   
                    cell.imageIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",self.positionArray[position]]];
                }else if ([obj.status integerValue] == 1) {
                    cell.imageIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"n_%@",self.positionArray[position]]];;
                }
                if([obj.id integerValue] ==[self.currentStap.id integerValue]){
                    cell.imageIcon.image = [UIImage imageNamed:[NSString stringWithFormat:@"s_%@",self.positionArray[position]]];;
                }
                isExit = YES;
                break;
            }
          
        }
        if(isExit == NO){
            WSJLog(@"第%@行被指控了",@(position));
            cell.imageIcon.image = nil;
            
        }
        
        }
         return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    //1 课程 2专题  3 考试  4积分
    weakSelf_define;
    [self.trainingDetail.campUserSteps enumerateObjectsUsingBlock:^(BTTrainingStapModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    
        if (obj.postion == indexPath.row) {
            //没完成状态 并且不是当前要进行的阶段
            if ( [obj.status integerValue] == 0 && [obj.id integerValue] !=[weakSelf.currentStap.id integerValue]) {
                return;
            }

            
            switch ([obj.campStepType integerValue] ) {
                case 1:{
                    BTCourseDetailVC *vc = [BTCourseDetailVC new];
                    if ([obj.status integerValue] == 0) {
                        NSDictionary *dict =@{@"finished":@(NO),@"id":obj.id};
                        vc.traingCampDict =[NSMutableDictionary dictionaryWithDictionary:dict];
                    }
                    
                    vc.courseId = [obj.targetID integerValue];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    break;
                }
                case 2:{
                    BTTopicDetailVC *vc =[BTTopicDetailVC new];
                    if ([obj.status integerValue] == 0) {
                        NSDictionary *dict =@{@"finished":@(NO),@"id":obj.id};
                        vc.traingCampDict =[NSMutableDictionary dictionaryWithDictionary:dict];
                    }
                    vc.topicId = [obj.targetID integerValue];
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    
                  
                
                    break;
                }
                case 3:
                   
                     [self gotoTestHtml5WithExamId:[obj.targetID integerValue]];
                  
                    break;
                case 4:
                    //            当前没有关卡
                    if ([obj.status integerValue] == 0) {
                           [self getRewardWithId:[obj.id integerValue]];
                    }
                  
                 
                   
                    break;
                default:
                    break;
                }
            
            
            return;
        }
     }];
    
}
#pragma -mark 进入考试界面
- (void)gotoTestHtml5WithExamId:(NSInteger)examId{
    BTBaseWebVC *vc =[BTBaseWebVC new];
    NSString *baseUrl = [[BTNetworkManager sharedMg] getBaseUrl];
    //拼接id
    NSString *url = [NSString stringWithFormat:@"%@/%@/%@",baseUrl,kStartExam,@(examId)];
    vc.url = url;
    vc.tagKey = @"exam";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController pushViewController:vc animated:YES];
    
 
}

- (void)getRewardWithId:(NSInteger)targetId{
  
    NSString *url = [NSString stringWithFormat:@"%@/%@",kGetRewardIntraning,@(targetId)];
    weakSelf_define;
    [[BTNetworkManager sharedMg] GET:url parameters:url success:^(id responseObject) {
        if (responseObject_success) {
            [[WSJPopview sharedWsjPopView] showFinishiedReward];
            [[WSJPopview sharedWsjPopView] showTrainingcampFinishing];
            [weakSelf requestTrainingDetail];
        }
        
    } failure:^(NSString *err) {
        
    }];

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestTrainingDetail];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}
@end
